package com.choosefine.springboot.devops.base.moudle.checkable;

import com.choosefine.springboot.devops.base.common.bean.CommonToolkitBean;
import com.choosefine.springboot.devops.base.common.bean.SimpleTemplateBean;
import com.choosefine.springboot.devops.base.common.component.InputMessage;
import com.choosefine.springboot.devops.base.moudle.event.EventCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

/**
 * Created by 邱鹏 on 2016/10/24.
 */
@Service
public class MessageService {
    Logger log = LoggerFactory.getLogger("微信/MessageService");
    @Autowired
    Properties yaml;
    @Autowired
    CommonToolkitBean commonToolkitBean;
    @Autowired
    Map<String, EventCallback> eventCallbackMap;

    public void text(InputMessage inputMsg, Map tplDataMap, HttpServletRequest request, HttpServletResponse response) {
        try {
            String defaultWord = yaml.get("msg.return.passive.txt.defaultWord") + "";
            log.info("defaultWord ：" + defaultWord);
            String content = new String(defaultWord.getBytes("utf-8"), "ISO8859_1");//必须强制转码，否则无法显示
            tplDataMap.put("content", content);
            SimpleTemplateBean stb = commonToolkitBean.simpleTemplateBean;
            String template = yaml.get("msg.return.passive.txt") + "";
            //将对象转换为XML字符串
            String xml = stb.template(template, tplDataMap, SimpleTemplateBean.TemplateType.DOLLAR);
            log.info("回复的消息：" + xml);
            //将内容发送给微信服务器，发送到用户手机
            response.getWriter().write(xml);
        } catch (Exception ex) {
            log.info("消息接受和发送出现异常!");
            ex.printStackTrace();
        }
    }

    public void event(InputMessage inputMsg, Map tplDataMap, HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info(inputMsg == null ? "null event类型的消息:" : "inputMsg有值,inputMsg.getEvent()："+inputMsg.getEvent());
        if (inputMsg == null) {
            response.getWriter().write("");
        } else {
            try {
                EventCallback callback = eventCallbackMap.get(inputMsg.getEvent());
                callback.execute(inputMsg, tplDataMap, request, response);
            } catch (Exception ex) {
                log.info("消息接受和发送出现异常!");
                ex.printStackTrace();
            }
        }
    }
}
